package com.boot.security.server.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boot.security.server.annotation.LogAnnotation;
import com.boot.security.server.common.Result;
import com.boot.security.server.common.ResultBuilder;
import com.boot.security.server.contant.Constant;
import com.boot.security.server.dao.AnnexDao;
import com.boot.security.server.dao.MOverseeQuestionDao;
import com.boot.security.server.dict.mapper.DataDictDetailsMapper;
import com.boot.security.server.dict.service.IDictService;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.mapper.MAnnexMapper;
import com.boot.security.server.mapper.MOverseeQuestionMapper;
import com.boot.security.server.mapper.SysRoleMapper;
import com.boot.security.server.mapper.SysRoleUserMapper;
import com.boot.security.server.model.Annex;
import com.boot.security.server.model.OverseeQuestion;
import com.boot.security.server.model.domain.MAnnex;
import com.boot.security.server.model.domain.MOverseeQuestion;
import com.boot.security.server.model.domain.SysRole;
import com.boot.security.server.model.domain.SysRoleUser;
import com.boot.security.server.model.param.OverseeQuestionParam;
import com.boot.security.server.model.param.UploadParam;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.MOverseeQuestionService;
import com.boot.security.server.service.SysLogService;
import com.boot.security.server.user.mapper.SysUserMapper;
import com.boot.security.server.user.model.SysUser;
import com.boot.security.server.user.model.SysUsers;
import com.boot.security.server.user.service.UserService;
import com.boot.security.server.utils.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mOverseeQuestions")
public class MOverseeQuestionController {

    @Autowired
    private SysLogService logService;
    @Autowired
    private UserService userService;

    @Autowired
    private MOverseeQuestionDao mOverseeQuestionDao;
    @Autowired
    private MOverseeQuestionMapper overseeQuestionMapper;
    @Autowired
    private MAnnexMapper mAnnexMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private MOverseeQuestionService mOverseeQuestionService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AnnexDao annexDao;
    @Autowired
    private IDictService dictService;
    @Autowired
    private DataDictDetailsMapper detailsMapper;


    @PostMapping("/save")
    @ApiOperation(value = "录入问题")
    @LogAnnotation
    public Result saveQuestion (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));

        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        return mOverseeQuestionService.saveQuestion(param);
    }


    @PostMapping("/saveDrafts")
    @ApiOperation(value = "录入保存至草稿箱")
    @LogAnnotation
    public Result saveDrafts (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));

        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        return mOverseeQuestionService.saveDrafts(param);
    }


    @PostMapping("/updateDrafts")
    @ApiOperation(value = "录入草稿箱修改")
    @LogAnnotation
    public Result updateDrafts (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));

        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        return mOverseeQuestionService.updateDrafts(param);
    }


    @PostMapping("/draftsSave")
    @ApiOperation(value = "录入草稿箱提交")
    @LogAnnotation
    public Result draftsSave (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));

        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        return mOverseeQuestionService.draftsSave(param);
    }


    @PostMapping("/feedBack")
    @ApiOperation(value = "问题跟踪反馈")
    @LogAnnotation
    public Result feedBack (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        if (StringUtils.isNotBlank(param.getRemark())) {
            param.setRemark(XssUtils.convertstr(param.getRemark()));
        }
        int oid = 0;
        try {
            oid = UserUtil.getLoginUser().getId().intValue();
        } catch (Exception e) {
            return ResultBuilder.paramError("请重新登录");
        }
        param.setOverseeId(oid);
        if (StringUtils.isNotBlank(param.getQuestionDetail())) {
            param.setQuestionDetail(XssUtils.convertstr(param.getQuestionDetail()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));
        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        try {
            return mOverseeQuestionService.feedBack(param);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResultBuilder.systemError("反馈失败！");
    }

    @PostMapping("/add")
    @LogAnnotation
    @ApiOperation(value = "保存")
    public OverseeQuestion save (@RequestBody OverseeQuestion questionStatus) {
        mOverseeQuestionDao.save(questionStatus);
        return questionStatus;
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询问题")
    public OverseeQuestionParam get (@PathVariable Long id) {
        MOverseeQuestion mOverseeQuestion = overseeQuestionMapper.selectByPrimaryKey(id);
        OverseeQuestionParam param = BeanHelper.copyProperties(mOverseeQuestion, OverseeQuestionParam.class);
        param.setQuestionId(mOverseeQuestion.getId());

        param.setQuestionDetail(XssUtils.convertStr(param.getQuestionDetail()));

        param.setQuestion(XssUtils.convertStr(param.getQuestion()));

        param.setLiaison(XssUtils.convertStr(param.getLiaison()));

        return param;
    }


    @PostMapping("/updateQuestion")
    @ApiOperation(value = "根据id修改问题")
    @LogAnnotation
    public Result updateQuestion (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        if (StringUtils.isNotBlank(param.getRemark())) {
            param.setRemark(XssUtils.convertstr(param.getRemark()));
        }
        param.setQuestion(XssUtils.convertstr(param.getQuestion()));

        param.setLiaison(XssUtils.convertstr(param.getLiaison()));
        int oid = 0;
        try {
            oid = UserUtil.getLoginUser().getId().intValue();
        } catch (Exception e) {
            return ResultBuilder.paramError("请重新登录");
        }
        param.setOverseeId(oid);
        return mOverseeQuestionService.updateQuestion(param);
    }

    @PutMapping
    @LogAnnotation
    @ApiOperation(value = "修改")
    public OverseeQuestion update (@RequestBody OverseeQuestion mOverseeQuestion) {
        mOverseeQuestionDao.update(mOverseeQuestion);
        return mOverseeQuestion;
    }

    @GetMapping("/list")
    @ApiOperation(value = "代办列表")
    public PageTableResponse list (PageTableRequest request) {
        return mOverseeQuestionService.list(request);
    }

    @GetMapping("/allList")
    @ApiOperation(value = "汇总列表")
    public PageTableResponse allList (PageTableRequest request) {
        return mOverseeQuestionService.allList(request);
    }

    /**
     *
     **/
    @GetMapping("/pool")
    @ApiOperation(value = "年度汇总附列表")
    public PageTableResponse pool (PageTableRequest request) {
        if (request.getParams().get(Constant.BRANCH) != null && request.getParams().get(Constant.BRANCH) != "") {
            String branch = request.getParams().get(Constant.BRANCH).toString();
            List<String> type = JSONObject.parseArray(branch, String.class);
            request.getParams().put(Constant.BRANCH, type);
        } else {
            request.getParams().remove(Constant.BRANCH);
        }
        if (request.getParams().get(Constant.START_PATROL_TIME) != null && request.getParams().get(Constant.START_PATROL_TIME) != "") {
            String startPatrolTime = request.getParams().get(Constant.START_PATROL_TIME).toString();
            List<String> type = JSONObject.parseArray(startPatrolTime, String.class);
            request.getParams().put(Constant.START_PATROL_TIME, type);
        } else {
            request.getParams().remove(Constant.START_PATROL_TIME);
        }
        // 判断身份
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser.getId() != null) {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserid(loginUser.getId().intValue());
            List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
            List<String> names = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(roleUsers)) {
                roleUsers.forEach(roleUser -> {
                    SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                    names.add(role.getName());
                });
            }
            if (names.contains(Constant.DBADMIN)) {
                // 本人
                SysUsers user = userService.getById(loginUser.getId().longValue());
                // 本人下级
                List<SysUsers> byPid = userService.getByPid(user.getId().intValue());
                List<Long> collect = byPid.stream().map(SysUsers::getId).collect(Collectors.toList());
                // 查询本人提交和审核的问题
                List<Long> ids = new ArrayList<>();
                ids.addAll(collect);
                ids.add(user.getId());
                List<Long> userIds = ids.stream().distinct().collect(Collectors.toList());
                request.getParams().put("ids", userIds);
                request.getParams().put("delete", 2);
                request.getParams().put("type", 2);
            } else if (names.contains(Constant.SHADMIN)) {
                SysUser sysUser = sysUserMapper.selectByPrimaryKey(loginUser.getId());
                if (StringUtils.isNotBlank(sysUser.getBranch()) && org.springframework.util.StringUtils.isEmpty(request.getParams().get(Constant.BRANCH))) {
                    List<String> branchs = dictService.findBranchByUserIdAndCode();
                    request.getParams().put("branch", branchs);
                    request.getParams().put("type", 2);
                    request.getParams().put("delete", 2);
                }
            } else {
                request.getParams().put("type", 2);
                request.getParams().put("delete", 2);
            }
        }

        return new PageTableHandler(new CountHandler() {

            @Override
            public int count (PageTableRequest request) {
                return annexDao.count(request.getParams());
            }
        }, new ListHandler() {

            @Override
            public List<Annex> list (PageTableRequest request) {
                List<Annex> list = annexDao.list(request.getParams(), request.getOffset(), request.getLimit());
                for (Annex annex : list) {
                    File startFile = new File(annex.getPath());
                    String fileName = startFile.getName();
                    try {
                        annex.setPath(fileName.substring(15));
                    } catch (Exception e) {
                        System.out.println("附件名称有误");
                    }
                    SysUsers byId = userService.getById(annex.getOverseeId().longValue());
                    annex.setOversee(byId.getNickname());
                }
                return list;
            }
        }).handle(request);
    }

    @GetMapping("/detailList")
    @ApiOperation(value = "详细列表")
    public PageTableResponse detailList (PageTableRequest request) {
        return mOverseeQuestionService.detailList(request);
    }

    @GetMapping("/yibanList")
    @ApiOperation(value = "列表")
    public PageTableResponse yibanList (PageTableRequest request) {
        return mOverseeQuestionService.yibanList(request);
    }

    @GetMapping("/draftsList")
    @ApiOperation(value = "列表")
    public PageTableResponse draftsList (PageTableRequest request) {
        return mOverseeQuestionService.draftsList(request);
    }

    @GetMapping("/getList")
    @ApiOperation(value = "过滤查询")
    public String getList () {
        OverseeQuestionParam param = new OverseeQuestionParam();
        List<OverseeQuestion> questionPageInfos = mOverseeQuestionDao.getList(param);
        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(questionPageInfos));

        HashMap<String, Object> map = new HashMap<>(4);
        map.put("count", questionPageInfos.size());
        map.put("data", objects);
        map.put("code", 0);
        map.put("msg", "");

        System.out.println("overseeQuestionPageInfo = " + JSONUtils.toJSONString(map));
        return JSONUtils.toJSONString(map);
    }

    @DeleteMapping("/{id}")
    @LogAnnotation
    @ApiOperation(value = "删除")
    public void delete (@PathVariable Long id) {
        mOverseeQuestionDao.delete(id);
    }

    @RequestMapping("/excel")
    @ApiOperation(value = "汇总列表导出", notes = "汇总列表导出")
    public void getList (HttpServletRequest request,HttpServletResponse response, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "year", required = false) String year, @RequestParam(value = Constant.BRANCH, required = false) String branch, @RequestParam(value = "userId", required = true) Integer userId) {
        String ip = IpUtils.getIpAddress(request);

        logService.save(userId.longValue(),"汇总列表导出",true,ip);

        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(type)) {
            List<String> types = JSONObject.parseArray(type, String.class);
            params.put(Constant.QUESTION_TYPE, types);
        } else {
            params.remove(Constant.QUESTION_TYPE);
        }
        if (StringUtils.isNotBlank(branch)) {
            List<String> branchs = JSONObject.parseArray(branch, String.class);
            params.put(Constant.BRANCH_ID, branchs);
        } else {
            params.remove(Constant.BRANCH_ID);
        }
        if (StringUtils.isNotBlank(year)) {
            List<String> years = JSONObject.parseArray(year, String.class);
            params.put(Constant.START_PATROL_TIME, years);
        } else {
            params.remove(Constant.START_PATROL_TIME);
        }
        // 查询名称
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);

        // 判断身份
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserid(userId);
        List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
        List<String> names = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            roleUsers.forEach(roleUser -> {
                SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                names.add(role.getName());
            });
        }
        if (names.contains(Constant.DBADMIN)) {
            params.put("overseeId", userId);
            params.put("checkStatus", Constant.CHECK_SUCCESS);
        } else if (names.contains(Constant.SHADMIN)) {
            params.put("reviewer", sysUser.getUsername());
            params.put("checkStatus", Constant.CHECK_SUCCESS);
        }

        List<OverseeQuestion> mOverseeQuestions = mOverseeQuestionDao.excelList(params);
        for (OverseeQuestion mOverseeQuestion : mOverseeQuestions) {
            SysUsers user = userService.getUser(mOverseeQuestion.getOversee());
            mOverseeQuestion.setOversee(user.getNickname());
            mOverseeQuestion.setLiaison(user.getNickname());
        }
        mOverseeQuestionService.export(mOverseeQuestions, response);
    }


    @RequestMapping(value = "/excelByIds")
    @ApiOperation(value = "汇总列表导出选择导出", notes = "汇总列表导出")
    public void excelByIds (HttpServletRequest request,HttpServletResponse response, @RequestParam("ids") String ids) {
        String ip = IpUtils.getIpAddress(request);

        logService.save(1L,"汇总列表导出选择导出",true,ip);
        List<Integer> integers = JSONObject.parseArray(ids, Integer.class);
        List<OverseeQuestion> mOverseeQuestions = mOverseeQuestionDao.excelIds(integers);
        for (OverseeQuestion mOverseeQuestion : mOverseeQuestions) {
            SysUsers user = userService.getUser(mOverseeQuestion.getOversee());
            mOverseeQuestion.setLiaison(user.getNickname());
            mOverseeQuestion.setOversee(user.getNickname());
        }
        mOverseeQuestionService.export(mOverseeQuestions, response);
    }


    @RequestMapping(value = "/excelDetail")
    @ApiOperation(value = "督办明细台账导出", notes = "督办明细台账导出")
    public void getSeekerList (HttpServletRequest request,HttpServletResponse response, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "year", required = false) String year, @RequestParam(value = Constant.BRANCH, required = false) String branch, @RequestParam(value = "userId", required = true) Integer userId) {
        String ip = IpUtils.getIpAddress(request);

        logService.save(userId.longValue(),"明细台账导出",true,ip);
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(type)) {
            List<String> types = JSONObject.parseArray(type, String.class);
            params.put(Constant.QUESTION_TYPE, types);
        } else {
            params.remove(Constant.QUESTION_TYPE);
        }
        if (StringUtils.isNotBlank(branch)) {
            List<String> branchs = JSONObject.parseArray(branch, String.class);
            params.put(Constant.BRANCH_ID, branchs);
        } else {
            params.remove(Constant.BRANCH_ID);
        }
        if (StringUtils.isNotBlank(year)) {
            List<String> years = JSONObject.parseArray(year, String.class);
            params.put(Constant.START_PATROL_TIME, years);
        } else {
            params.remove(Constant.START_PATROL_TIME);
        }
        // 查询名称
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        // 判断身份
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserid(userId);
        List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
        List<String> names = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            roleUsers.forEach(roleUser -> {
                SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                names.add(role.getName());
            });
        }
        if (names.contains(Constant.DBADMIN)) {
            params.put("overseeId", userId);
            params.put("checkStatus", Constant.CHECK_SUCCESS);
        } else if (names.contains(Constant.SHADMIN)) {
            params.put("reviewer", sysUser.getUsername());
            params.put("checkStatus", Constant.CHECK_SUCCESS);
        }

        List<OverseeQuestion> mOverseeQuestions = mOverseeQuestionDao.excelList(params);
        if (CollectionUtils.isNotEmpty(mOverseeQuestions)) {
            for (OverseeQuestion param : mOverseeQuestions) {
                param.setQuestionDetail(XssUtils.convertStr(param.getQuestionDetail()));

                param.setQuestion(XssUtils.convertStr(param.getQuestion()));

                param.setLiaison(XssUtils.convertStr(param.getLiaison()));

                SysUsers user = userService.getUser(param.getOversee());
                param.setOversee(user.getNickname());

            }
            mOverseeQuestionService.exportDetailed(mOverseeQuestions, response);
        }
    }


    @RequestMapping(value = "/excelDetailByIds")
    @ApiOperation(value = "督办明细台账选择导出", notes = "督办明细台账导出")
    public void excelDetailByIds (HttpServletRequest request,HttpServletResponse response, @RequestParam("ids") String ids) {
        String ip = IpUtils.getIpAddress(request);
        logService.save(1L,"督办明细台账选择导出",true,ip);
        List<Integer> integers = JSONObject.parseArray(ids, Integer.class);
        List<OverseeQuestion> mOverseeQuestions = mOverseeQuestionDao.excelIds(integers);
        if (CollectionUtils.isNotEmpty(mOverseeQuestions)) {
            for (OverseeQuestion param : mOverseeQuestions) {
                param.setQuestionDetail(XssUtils.convertStr(param.getQuestionDetail()));

                param.setQuestion(XssUtils.convertStr(param.getQuestion()));

                param.setLiaison(XssUtils.convertStr(param.getLiaison()));

                SysUsers user = userService.getUser(param.getOversee());
                param.setOversee(user.getNickname());
            }
            mOverseeQuestionService.exportDetailed(mOverseeQuestions, response);
        }
    }

    /**
     * excelDetailByIds
     **/
    @PostMapping(value = "/uploadSource", produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    @LogAnnotation
    @ApiOperation(value = "上传附件", notes = "上传附件")
    public String uploadSource (@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {

        String header = request.getHeader(" Accep");

        response.setContentType("text/html;charset=utf-8");

        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("\\") + 1);

        String pathString = null;
        if (file != null) {
            pathString = "D:/upload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + substring;
        }
        try {
            File files = new File(pathString);
            if (! files.getParentFile().exists()) {
                files.getParentFile().mkdirs();
            }
            file.transferTo(files);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HashMap<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", pathString);

        return JSONObject.toJSONString(map);
    }

    @RequestMapping(value = "/fileList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> fileList (@RequestParam("id") Integer id, HttpServletRequest request) {
        Integer type = 0;
        // 判断身份
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser != null && loginUser.getId() != null) {
            MOverseeQuestion mOverseeQuestion = overseeQuestionMapper.selectByPrimaryKey(id);
            if (mOverseeQuestion.getOverseeId().equals(loginUser.getId().intValue())){
                type = 2;
            }else {
                type = 3;
            }

        }
        // 查询跟踪记录
        Example example = new Example(MAnnex.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("questionId", id);
        criteria.andNotEqualTo("delated", 2);
        criteria.andEqualTo("type", 1);

        List<MAnnex> select = mAnnexMapper.selectByExample(example);
        for (MAnnex annex : select) {
            // 复用type字段前端区分
            annex.setType(type);
            File startFile = new File(annex.getPath());
            String fileName = startFile.getName();
            annex.setPath(fileName.substring(15));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", select.size());
        map.put("data", select);
        return map;
    }

    @RequestMapping(value = "/file", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> file (@RequestParam("id") Integer id,@RequestParam("userId") Integer userId, HttpServletRequest request) {

        return mOverseeQuestionService.file(id,userId);
    }

    @RequestMapping(value = "/saveReport", method = RequestMethod.POST)
    @ResponseBody
    public Result saveReport (@RequestBody UploadParam param) {
        System.out.println("param = " + param.getFile());
        if (StringUtils.isNotBlank(param.getFile())){
            String[] path = param.getFile().split(",");
            for (String s : path) {
                MAnnex mAnnex = new MAnnex();
                mAnnex.setBranch(param.getBranchName());
                mAnnex.setOverseeYear(param.getYear());
                mAnnex.setOverseeId(UserUtil.getLoginUser().getId().intValue());
                mAnnex.setType(2);
                mAnnex.setDelated(0);
                mAnnex.setCreateTime(new Date());
                mAnnex.setPath(s);
                mOverseeQuestionService.saveReport(mAnnex);
            }
            return ResultBuilder.success();
        }
        return ResultBuilder.paramError("请上传文件");


    }

    /**
     *
     **/
    @RequestMapping(value = "/downSource", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "下载附件", notes = "下载附件")
    public void downSource (@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) {
        String ip = IpUtils.getIpAddress(request);

        logService.save(1L,"下载附件",true,ip +"==附件"+id);
        List<Integer> integers = JSONObject.parseArray(id, Integer.class);
        // 查询文件路径
        if (integers.size() == 1) {
            MAnnex mAnnex = mAnnexMapper.selectByPrimaryKey(integers.get(0));
            if (mAnnex != null && StringUtils.isNotBlank(mAnnex.getPath())) {
                HttpServletResponse download = DownFile.download(mAnnex.getPath(), response);
            }
        } else {
            List<String> paths = new ArrayList<>();
            for (Integer integer : integers) {
                MAnnex annex = mAnnexMapper.selectByPrimaryKey(integer);
                paths.add(annex.getPath());
            }
            // 压缩包临时路径
            String path = "D:/upload/down/";
            // 压缩包名称
            String fileName = "附件压缩包.zip";
            try {
                FileUtil.downloadFilesTest(request, response, paths, path, fileName);
            } catch (IOException e) {

                return;
            }
        }
    }

    /**
     *
     **/
    @RequestMapping(value = "/deletePathOne", method = RequestMethod.GET)
    @ResponseBody
    @LogAnnotation
    @ApiOperation(value = "督办申请删除附件", notes = "督办申请删除附件")
    public void deletePathOne (@RequestParam("id") Integer id, HttpServletRequest request,HttpServletResponse response) {

        mOverseeQuestionService.deletePathOne(id);
    }

    @RequestMapping(value = "/deletePathDrafs", method = RequestMethod.GET)
    @ResponseBody
    @LogAnnotation
    @ApiOperation(value = "删除草稿箱附件", notes = "删除草稿箱附件")
    public void deletePathDrafs (@RequestParam("id") Integer id, HttpServletResponse response) {
        mOverseeQuestionService.deletePathDrafs(id);
    }

    /**
     *
     **/
    @RequestMapping(value = "/deleteYearReport", method = RequestMethod.GET)
    @ResponseBody
    @LogAnnotation
    @ApiOperation(value = "删除年度报告", notes = "删除年度报告")
    public Result deleteYearReport (@RequestParam("id") Integer id,HttpServletRequest request, HttpServletResponse response) {

        return mOverseeQuestionService.deleteYearReport(id);
    }

    @RequestMapping(value = "/OA/Login", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "代办跳转", notes = "代办跳转")
    public void agencyLogin (@RequestParam(value = "id", required = false) Integer id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        mOverseeQuestionService.agencyLogin(id, request, response);
    }

    /**
     *
     **/
    @RequestMapping(value = "/deletePathTwo", method = RequestMethod.GET)
    @ResponseBody
    @LogAnnotation
    @ApiOperation(value = "审核同意删除附件", notes = "审核同意删除附件")
    public void deletePathTwo (@RequestParam("id") Integer id, HttpServletResponse response,HttpServletRequest request) {

        mOverseeQuestionService.deletePathTwo(id);
    }

    @RequestMapping(value = "/deleteFile/{id}", method = RequestMethod.GET)
    @ResponseBody
    @LogAnnotation
    @ApiOperation(value = "代办跳转审核删除附件", notes = "代办跳转审核删除附件")
    public void deletePathTwo (HttpServletRequest request,HttpServletResponse response, @PathVariable Integer id) {

        mOverseeQuestionService.deletePathTwo(id);
    }

    /**
     * 审核同意
     * @param param
     * @return
     */
    @PostMapping("/agreeExamine")
    @LogAnnotation
    @ApiOperation(value = "审核同意", notes = "审核同意")
    public Result agreeExamine (@RequestBody OverseeQuestionParam param,HttpServletRequest request) {

        return mOverseeQuestionService.agreeExamine(param);
    }

    /**
     * 审核不同意
     * @param param
     * @return
     */
    @PostMapping("/notAgreeExamine")
    @LogAnnotation
    @ApiOperation(value = "审核不同意", notes = "审核不同意")
    public Result notAgreeExamine (@RequestBody OverseeQuestionParam param,HttpServletRequest request ) {

        return mOverseeQuestionService.notAgreeExamine(param);
    }

    @PostMapping("/getStatus/{id}")
    @ApiOperation(value = "获取状态")
    public String getStatus (@PathVariable Long id) {
        return mOverseeQuestionService.getStatus(id);
    }

    @PostMapping("/getYiBan/{id}")
    @ApiOperation(value = "获取已办事项")
    public String getYiBan (@PathVariable Integer id) {
        return mOverseeQuestionService.getYiBan(id);
    }

    @PostMapping("/getUser")
    @ApiOperation(value = "判断身份")
    public String getUser (HttpServletRequest request) {
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser == null) {
            return "0";
        }
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserid(loginUser.getId().intValue());
        List<SysRoleUser> roleUsers = sysRoleUserMapper.select(sysRoleUser);
        List<String> names = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            roleUsers.forEach(roleUser -> {
                SysRole role = roleMapper.selectByPrimaryKey(roleUser.getRoleid());
                names.add(role.getName());
            });
        }
        if (names.contains(Constant.DBADMIN)) {
            return "1";
        }
        return "0";
    }
}


